<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>注册页面</title>

<!-- 清楚默认样式 -->
<link rel="stylesheet" href="./../static/CSS/register.css">

<link rel="stylesheet" href="./../static/CSS/base.css">
</head>

<body>
<div class="register-container">
    <h2>账户注册</h2>
    <form id="register-form" action="/register" method="POST">
        <div class="input-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" maxlength="11" placeholder="请输入用户名" required>
        </div>
        <div class="input-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" maxlength="8" placeholder="请输入密码" required>
        </div>
        <div class="input-group">
            <input type="password" id="password2" name="password2"  maxlength="8"   placeholder="请再次输入密码" required>
        </div>
        <button type="submit">注册</button>
    </form>
    <p>
        已有账号？<a href="/login">立即登录</a>
    </p>
    </div>

    <script>
        async function checkCredentials(event) {
          event.preventDefault(); // 阻止表单默认提交

        const form = document.getElementById('register-form');
        const formData = new FormData(form);
        const usernameInput = document.getElementById('username');
        const passwordInput = document.getElementById('password');
        const password2Input = document.getElementById('password2');

        try {
            const response = await fetch('/register', {
            method: 'POST',
            body: formData,
            });

            if (response.redirected) {
              // 注册成功，跳转
            alert("注册成功")
            window.location.href = response.url;
            } else {
                const errorText = await response.text();

                if (errorText.includes("用户已存在")) {
                    usernameInput.value = "";
                    passwordInput.value = "";
                    password2Input.value = "";
                    alert("此用户名已被注册");
                } else if (errorText.includes("密码不一致")) {
                    // 清空输入的密码
                    passwordInput.value = "";
                    password2Input.value = "";
                    alert("两次输入的密码不一致，请重新输入");
                } else {
                    // 其他错误
                    alert(errorText);
                }
                }
            } catch (error) {
                alert("网络错误，请重试");
            }
        }

        // 绑定表单提交事件
        document.getElementById('register-form').addEventListener('submit', checkCredentials);
    </script>
</body>

</html>